<template>
    <div id="commodity-lower-list">
      <div class="search-box">
        <Row type="flex">
          <Row type="flex" justify="start" class="search-item-left">
            <Col class="search-item"><span class="search-label">输入搜索：</span><Input placeholder="分类编码/分类名称" v-model='searchName'></Input></Col>
            <!-- <Col class="search-item">
              <span class="search-label">分类级别：</span>
              <Select v-model="searchObj.classify" @on-change="search" style="width:180px" placeholder='请选择分类级别'>
                <Option v-for="item in classifyList" :value="item.value" :key="item.value">{{ item.label }}</Option>
              </Select>
            </Col> -->
            <Col class="search-item">
              <Button class="search-btn" type='primary' @click="doSearch">查询</Button>
            </Col>
            <Col class="search-item">
              <Button class="search-btn" @click="reset">重置</Button>
            </Col>
          </Row>
          <Row type="flex" justify="end" class="search-item-right">
            <Col class="search-item"><Button class="search-btn" type="primary" style="margin-right:8px" @click="skipAdd" v-if="hasPermission('moms:product:categoryaddchild')">添加分类</Button></Col>
          </Row>
        </Row>
      </div>
      <Table stripe class="table-list" :columns="columns" :data="tableData" :loading="loading" :height="tableHeight" @on-sort-change='changeSort'>
        <template slot-scope="{ row }" slot="level">
          <span>{{row.parentId ? '二级': '一级'}}</span>
        </template>
        <template slot-scope="{ row }" slot="isShow">
          <span>{{row.isShow === 0 ? '隐藏' : row.isShow === 1 ?'显示': ''}}</span>
          <!-- <i-switch :value='!!row.isShow'>
            <span slot="open">开</span>
            <span slot="close">关</span>
          </i-switch> -->
        </template>
        <template slot-scope="{ row }" slot="action">
          <i class="iconsys iconedit" title="编辑" @click='skipEdit(row)' v-if="hasPermission('moms:product:categoryupdate')"></i>
          <Poptip confirm title="确认删除此数据吗？" transfer @on-ok="sureDel(row)" style="text-align:left">
            <i class="iconsys icondel" title="删除" v-if="hasPermission('moms:product:categorydelete')"></i>
          </Poptip>
          <i class="iconsys iconzhuanyi" title="转移商品" @click='skipTransfer(row)' v-if="hasPermission('moms:product:categorytransferchild')"></i>
        </template>
      </Table>
      <Row type='flex' justify="end" style='padding: 20px'>
        <Col>
          <Page :total="pageObj.total"
                :page-size='pageObj.pageSize'
                :current='pageObj.pageIndex'
                :page-size-opts='[20,50,100,200]'
                show-total
                show-sizer
                @on-change='changePageIndex'
                @on-page-size-change='changePageSize' />
        </Col>
      </Row>
      <Modal v-model="modalShow" width="480" title="转移商品" :closable='false'>
        <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="110" style="margin:20px 0 0 15px">
          <FormItem label="原商品分类：" prop="prevClassify">
            <Input placeholder="原商品分类" v-model='formValidate.prevClassify' disabled style="width:200px"></Input>
          </FormItem>
          <FormItem label="目标商品分类：" prop="targetClassify">
            <!-- <Select v-model="formValidate.targetClassify" style="width: 180px">
              <Option v-for="(item, index) in targetClassifyList" :value="item.categoryId" :key="index" :disabled="sourceCategoryId === item.categoryId? true:false">{{ item.categoryName }}</Option>
            </Select> -->
            <Select v-model="formValidate.targetClassify" style="width:200px">
              <OptionGroup :label="ele.categoryName" v-for="(ele, idx) in targetClassifyList" :key='idx'>
                <Option v-for="item in ele.subCategoryList" :value="item.categoryId" :key="item.categoryId" :disabled="sourceCategoryId === item.categoryId? true:false">{{ item.categoryName }}</Option>
              </OptionGroup>
            </Select>
          </FormItem>
        </Form>
        <div slot="footer">
          <Button style="width:78px;margin-right:10px" @click='cancel'>取消</Button>
          <Button type="primary" style="width:78px" @click="startTransfer">开始转移</Button>
        </div>
      </Modal>
    </div>
  </template>

<script>
import { getClassifyList, delClassify, transferProduct } from '@/api/commondity/index'
export default {
  name: 'commodity_lower_list',
  computed: {
    tableHeight () {
      let height = this.tableData.length > 10 ? 520 : 0
      return height
    }
  },
  watch: {
    '$route' (newRoute) {
      if (newRoute.name === 'commodity_lower_list') {
        this.getData()
      }
    },
    modalShow (status) {
      if (!status) {
        this.goodsNum = 0
      }
    }
  },
  data () {
    return {
      sortBy: 'desc',
      goodsNum: 0,
      sourceCategoryId: '',
      modalShow: false,
      loading: false,
      searchName: '',
      targetClassifyList: [],
      formValidate: {
        prevClassify: '',
        targetClassify: ''
      },
      ruleValidate: {
        targetClassify: { required: true, message: '请选择目标分类', trigger: 'change' }
      },
      searchObj: {
        searchName: ''
      },
      pageObj: {
        total: 0,
        pageIndex: 1,
        pageSize: 20
      },
      tableData: [],
      columns: [
        {
          title: '分类编码',
          key: 'categoryId',
          sortable: 'custom'
        },
        {
          title: '分类名称',
          key: 'categoryName'
        },
        {
          title: '级别',
          slot: 'level'
        },
        {
          title: '排序',
          key: 'seq'
          // sortable: true
        },
        {
          title: '商品数量',
          key: 'goodsNum'
        },
        {
          title: '是否显示',
          slot: 'isShow'
        }
        // {
        //   title: '操作',
        //   slot: 'action',
        //   width: 160
        // }
      ]
    }
  },
  methods: {
    changeSort (column, key, order) {
      this.sortBy = column.order
      this.getData()
    },
    doSearch () {
      this.searchObj.searchName = this.searchName
      this.pageObj.pageIndex = 1
      this.getData()
    },
    reset () {
      this.searchObj.searchName = ''
      this.searchName = ''
      this.pageObj.pageIndex = 1
      this.pageObj.pageSize = 20
      this.getData()
    },
    skipAdd () {
      this.$router.push({ name: 'classify_create', query: { id: this.$route.params.id, type: '2' } })
    },
    skipEdit (row) {
      this.$router.push({ name: 'classify_edit', params: { id: row.categoryId }, query: { categoryId: this.$route.params.id, type: '2' } })
    },
    skipTransfer (row) {
      this.modalShow = true
      this.sourceCategoryId = row.categoryId
      this.formValidate.prevClassify = row.categoryName
      this.goodsNum = row.goodsNum
      this.getLevelList()
    },
    sureDel (row) {
      delClassify({
        merchantId: this.$store.state.user.merchantId,
        categoryId: row.categoryId,
        categoryType: '0'
      }).then(res => {
        if (res.data.status === 200) {
          this.$Message.success('删除成功!')
          this.getData()
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    cancel () {
      this.modalShow = false
    },
    startTransfer () {
      this.$refs.formValidate.validate(valid => {
        if (valid) {
          if (this.goodsNum > 0) {
            transferProduct({
              merchantId: this.$store.state.user.merchantId,
              sourceCategoryId: this.sourceCategoryId,
              targetCategoryId: this.formValidate.targetClassify,
              updater: this.$store.state.user.userId,
              updaterName: this.$store.state.user.userName
            }).then(res => {
              if (res.data.status === 200) {
                this.$Message.success('转移成功!')
                this.getData()
                this.modalShow = false
              } else {
                this.$Message.error(`${result.error}`)
              }
            })
          } else {
            this.$Message.error('无商品不可转移')
          }
        }
      })
    },
    changePageIndex (index) {
      this.pageObj.pageIndex = index
      this.getData()
    },
    changePageSize (size) {
      this.pageObj.pageSize = size
      this.pageObj.pageIndex = 1
      this.getData()
    },
    // 获取所有的二级分类
    getLevelList () {
      getClassifyList({
        merchantId: this.$store.state.user.merchantId,
        isShow: 1
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.targetClassifyList = result.data.categories || []
        } else {
          this.$Message.error(`${result.error}`)
        }
      })
    },
    getData () {
      this.loading = true
      getClassifyList({
        merchantId: this.$store.state.user.merchantId,
        level: '2',
        keyword: this.searchObj.searchName,
        parentCategoryId: this.$route.params.id,
        offset: this.pageObj.pageSize * (this.pageObj.pageIndex - 1),
        limit: this.pageObj.pageSize,
        sortBy: this.sortBy
      }).then(res => {
        this.loading = false
        const result = res.data || {}
        if (result.status === 200) {
          this.tableData = result.data.categories || []
          this.pageObj.total = result.data.total
          if (result.data.categories.length / this.pageObj.pageSize === 0) {
            if (this.pageObj.pageIndex > 1) {
              this.pageObj.pageIndex--
              this.getData()
            }
          }
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.loading = false
        this.$Message.error(`${err}`)
      })
    }
  },
  mounted () {
    this.getData()
    if (this.hasPermission(['moms:product:categoryupdate', 'moms:product:categorydelete', 'moms:product:categorytransferchild'])) {
      this.columns.push({
        title: '操作',
        slot: 'action',
        width: 200
      })
    }
  }
}
</script>
